package com.swj.common.core.utils;

import com.alibaba.fastjson2.JSONObject;
import com.swj.common.core.utils.ip.IpUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

/**
 * 定位工具类
 *
 * @author 10834
 */
public class LocaltionUtil {

    private static final String key ="56326a2c902aa29a3d7b831eb146b3b0";

    /**
     * 请求ip对应的地址经纬度
     * @return 定位信息
     */
    public  static String getLocation(){
        String ipString = IpUtils.getIpAddr();
        if (IpUtils.isNotEmptyIp(ipString)){
            if (IpUtils.internalIp(ipString)){
                return "本机";
            }else {
                String url = String.format("https://restapi.amap.com/v3/ip?key=%s&ip=%s&output=json", key, ipString);
                JSONObject jsonObject = new RestTemplate().getForObject(url, JSONObject.class);
                if(Objects.nonNull(jsonObject)
                        &&"1".equals(jsonObject.getString("status"))
                        &&(SysStringUtil.isNotEmpty(jsonObject.getString("province"))
                        ||SysStringUtil.isNotEmpty(jsonObject.getString("city")))){
                   return jsonObject.getString("province")+jsonObject.getString("city");
                }
            }
        }
        return "未知";
    }


}
